package morenoapp.components.common.table.renderer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;

/**
 *
 * @author dmitry.mamonov
 */
public class ProxyPanelTableCellRenderer extends JPanel implements TableCellRenderer {
    private TableCellRenderer delegate;
    private JComponent delegateComponent;

    public ProxyPanelTableCellRenderer(TableCellRenderer delegate) {
        if (delegate == null) {
            throw new NullPointerException("Delegate is null"); //NOI18N
        }
        this.delegate = delegate;
        this.delegateComponent = (JComponent) delegate;
        this.delegateComponent.setOpaque(false);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        paintBackground(g);
        delegateComponent.setOpaque(false);
        delegateComponent.setBounds(getBounds());
        delegateComponent.paint(g);
    }

    protected void paintBackground(Graphics g) {
        Color backup = g.getColor();
        Rectangle r = getBounds();
        g.setColor(Color.lightGray);
        final int step = 5;
        int start = -r.height - step + (r.height % step);
        for (int x = start; x < r.width; x += step) {
            g.drawLine(x, 0, x + r.height, r.height);
        }
        g.setColor(backup);
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, final boolean isSelected, boolean hasFocus, int row, int column) {
        boolean localIsSelected = isSelected;
        JTable.DropLocation dropLocation = table.getDropLocation();
        if (dropLocation != null && !dropLocation.isInsertRow() && !dropLocation.isInsertColumn() && dropLocation.getRow() == row && dropLocation.getColumn() == column) {
            localIsSelected = true;
        }
        if (localIsSelected) {
            this.setBackground(table.getSelectionBackground());
        } else {
            Color alternateBg = UIManager.getColor("Table.alternateRowColor"); //NOI18N
            if (alternateBg != null && row % 2 == 0) {
                this.setBackground(alternateBg);
            } else {
                this.setBackground(Color.WHITE);
            }
        }
        //System.out.println("val:=" + value + " fg = " + delegateComponent.getForeground() + " bg = "+getBackground());
        if (value != null && !"".equals(value) && !"<html>".equals(value)) { // NOI18N
            setToolTipText(value.toString());
        } else {
            setToolTipText(null);
        }
        //delegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
        delegate.getTableCellRendererComponent(table, value, false, hasFocus , row, column); //don't ever tell to delegate that we are selected.
        return this;
    }
}
